﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using Empires.Infrastructure.Entities.Entity;
using Empires.Tool.Framework;
using Empires.Infrastructure.Component.WorkPool;
using Empires.Infrastructure.Component.WorkPool.WorkHandle.Email;
using Empires.Biz.Configuration;
using Empires.Infrastructure.Entities;
using Empires.Infrastructure.Entities.EntityCache;

namespace Empires.Biz
{
    public class UserBiz
    {
        #region Account
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="NoEmail">true:不发邮件</param>
        /// <returns>注册失败返回null</returns>
        public static User Register(User member, bool NoEmail = false)
        {
            if (member != null && !String.IsNullOrEmpty(member.UserName)
                    && UserNotExists(member.UserName))
            {
                var token = new AccountToken()
                {
                    ExpireDate = DateTime.Now.AddDays(7),
                    Token = Guid.NewGuid().ToString(),
                    UserName = member.UserName
                };
                member.Token = token.Token;
                member.Password = AesAlgorithm.Encrypt(member.Password);
                member = member.PostAdd();
                if (member != null)
                {
                    if (!NoEmail)
                    {
                        string toMember = EmailBuilder.BuildRegisterActivtionEmail(
                            member.UserName, BuildFixToken(token));
                        if (!String.IsNullOrEmpty(toMember))
                        {
                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                Message = toMember,
                                Title = "账号激活邮件",
                                Recipient = member.UserName
                            });
                        }
                        //WorkPool.Append<AccountEmail>(WorkType.email_for_register, new AccountEmail()
                        //{
                        //    Recipient = member.UserName,
                        //    Token = BuildFixToken(token)
                        //});
                    }
                    return member;
                }
            }
            return null;
        }
        private static string BuildFixToken(AccountToken token)
        {
            string str = token.ToJson();
            return EncodeByBase64.Encode(str);
        }
        public static User CheckToken(string token)
        {
            if (String.IsNullOrEmpty(token))
            {
                return null;
            }
            token = EncodeByBase64.Decode(token);
            var accountToken = token.ToObject<AccountToken>();
            if (accountToken != null)
            {
                var user = new User().Find(accountToken.UserName);
                if (user != null)
                {
                    if (user.Token == accountToken.Token
                        && accountToken.ExpireDate > DateTime.Now)
                    {
                        user.Token = Guid.NewGuid().ToString();
                        user.PostModify();
                        return user;
                    }
                }
            }
            return null;
        }
        public static User Activation(string token)
        {
            var member = CheckToken(token);
            if (member != null)
            {
                member.IsActivate = true;
                if (member.PostModify() != null)
                {
                    return member;
                }
            }
            return null;
        }
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="rememberMe"></param>
        /// <returns>登陆失败返回null</returns>
        public static User Login(string userName, string password, bool rememberMe = false)
        {
            var user = new User().Find(userName);
            if (user != null && !user.IsRefuse)
            {
                if (user.Password == AesAlgorithm.Encrypt(password))
                {
                    if (!user.IsActivate)
                    {
                        return new User() { IsActivate = false };
                    }
                    FormsAuthentication.SetAuthCookie(userName, rememberMe);
                    return user;
                }
            }
            return null;
        }
        public static void LogOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();
        }
        /// <summary>
        /// true:不存在 false:存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool UserNotExists(string userName)
        {
            if (!String.IsNullOrEmpty(userName))
            {
                using (Context ctx = new Context())
                {
                    return !ctx.User.Any(c => c.UserName == userName);
                }
            }
            return false;
        }
        /// <summary>
        /// 发重置密码邮件
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool ResendForgotPasswordMail(string userName)
        {
            var user = new User().Find(userName);
            if (user != null)
            {
                var token = new AccountToken()
                {
                    ExpireDate = DateTime.Now.AddDays(1),
                    Token = Guid.NewGuid().ToString(),
                    UserName = userName
                };
                user.Token = token.Token;
                if (user.PostModify() != null)
                {
                    string toMember = EmailBuilder.BuildResetPasswordEmail(
                        user.UserName, BuildFixToken(token));
                    if (!String.IsNullOrEmpty(toMember))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                         new NormalNotifyEmail()
                         {
                             Message = toMember,
                             Title = SiteResource.SiteName + "--密码重置验证",
                             Recipient = user.UserName
                         });
                    }
                    //WorkPool.Append<AccountEmail>(WorkType.email_for_resetpassword, new AccountEmail()
                    //{
                    //    Recipient = user.UserName,
                    //    Token = BuildFixToken(token)
                    //});
                }
                return true;
            }
            return false;
        }
        public static User ChangePassword(string userName, string password)
        {
            if (!String.IsNullOrEmpty(userName) &&
                !String.IsNullOrEmpty(password))
            {
                var user = new User().Find(userName);
                if (user != null)
                {
                    user.Password = AesAlgorithm.Encrypt(password);
                    if (user.PostModify() != null)
                    {
                        new UserCache().RefreshItem(userName);
                        return user;
                    }
                }
            }
            return null;

        }
        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static User ChangePassword(string userName, string oldpassword, string password)
        {
            if (!String.IsNullOrEmpty(userName) &&
                !String.IsNullOrEmpty(password))
            {
                var user = new User().Find(userName);
                if (user != null)
                {
                    if (user.Password != AesAlgorithm.Encrypt(oldpassword))
                    {
                        return null;
                    }
                    user.Password = AesAlgorithm.Encrypt(password);
                    if (user.PostModify() != null)
                    {
                        return user;
                    }
                }
            }
            return null;
        }
        public static User ReSendActiveMail(string username)
        {
            if (String.IsNullOrEmpty(username))
            {
                return null;
            }
            var user = new User().Find(username);
            if (user != null && !user.IsActivate)
            {
                var token = new AccountToken()
                {
                    ExpireDate = DateTime.Now.AddDays(7),
                    Token = Guid.NewGuid().ToString(),
                    UserName = user.UserName
                };
                user.Token = token.Token;
                user = user.PostModify();
                if (user != null)
                {
                    string toMember = EmailBuilder.BuildRegisterActivtionEmail(
                            user.UserName, BuildFixToken(token));
                    if (!String.IsNullOrEmpty(toMember))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Message = toMember,
                            Title = "账号激活邮件",
                            Recipient = user.UserName
                        });
                    }
                    //WorkPool.Append<AccountEmail>(WorkType.email_for_register, new AccountEmail()
                    //{
                    //    Recipient = user.UserName,
                    //    Token = BuildFixToken(token)
                    //});
                    return user;
                }
            }
            return null;
        }
        public static User ChangeInfo(string username, string photo, string nickname, string birthday,
            int gender, int areaCode, int location, string email, string phone, string qq)
        {
            var user = new User().Find(username);
            if (user != null)
            {
                user.NickName = nickname;
                user.Birthday = birthday.ToDateTime(DateTime.Parse("1970-01-01"));
                user.Gender = (Infrastructure.Entities.Enum.Gender)gender;
                user.Phone = phone;
                user.QQ = qq;
                if (user.PostModify() != null)
                {
                    return user;
                }
            }
            return null;
        }

        #endregion


    }
    class AccountToken
    {
        public DateTime ExpireDate { get; set; }

        public string Token { get; set; }

        public string UserName { get; set; }
    }
}
